import random

from kivyx.widgets import ScatterPlane, Transform, Rectangle, Circle
from kivyx.widgets.camera import Camera
from kivyx.animation import Animation
from kivyx.lib import App
from kivyx.misc import show_bbox


class FooApp(App):
    def build(self):
        random.seed(0)

        rect = Rectangle()
        rect.rgba = (1, 0, 0, 1)
        rect.size = 100, 100
        rect.center = 0, 0

        circle1 = Circle()
        circle1.rgba = (0, 0, 1, 1)
        circle1.radius = 100
        circle1.center = 200, 100

        circle2 = Circle()
        circle2.rgba = (0, 1, 0, 1)
        circle2.radius = 80
        circle2.center = 0, 300

        self.transform = Transform()
        self.transform.debug_viewport = True
        self.transform.add_touch_handler(ignore_oov=False)

        from kivyx.widgets import Image
        img = Image(source=r"C:\Users\Rui\Pictures\CheckerPatternPaper.png",
                    allow_stretch=True, keep_ratio=False)
        self.transform.add_widget(img)
        img.pos = -2000, -2000
        img.size = 4000, 4000

        self.camera = Camera(transform=self.transform, controllers=[Camera.Follow(fit_ratio=0.5)])
        self.camera.viewport_max_vel = 2000
        self.camera.viewport_max_acc = 20000
        self.camera.scale_max_vel = 0.25
        # self.camera.scale_max_acc = 5.0
        show_bbox(self.camera, color=(1, 0, 0, 0.3))
        self.transform.viewport_pos = -500, 1000

        self.follow = self.camera.controllers[0]
        self.ballz = [circle1, circle2, rect]
        for widget in self.ballz:
            self.transform.add_widget(widget)
        self.follow.targets.update(self.ballz)

        root = ScatterPlane()
        root.add_widget(self.camera)
        # root = self.camera
        return root

    def on_start(self):
        self.camera.size = (self.root.width * 0.9, self.root.height * 0.9)
        self.camera.center = self.root.center
        self.camera.start()
        self.animate_widget()
        self.transform.viewport_pos = 10000, 10000
        self.camera.update_attrs_from_transform()

    def animate_widget(self, *args):
        widget = random.choice(self.ballz)
        x = random.randint(-20, 20) * 100
        y = random.randint(-20, 20) * 100
        anim = Animation(center_x=x, center_y=y, duration=random.randint(1, 3)).bound_to(widget)
        anim.bind(on_complete=self.animate_widget)
        anim.start()


FooApp().run()
